package TestFinal;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Inventory {
    private List<Product>products;
    private final String filepath = "C:\\Users\\bufu\\Desktop\\heimaproject\\Java2-9\\src\\TestFinal\\库存文件.txt";

    public Inventory() {
        products = new ArrayList<Product>();
        try(
                BufferedReader br = new BufferedReader(new FileReader(filepath));
        ){
            String line;
            while((line = br.readLine()) != null)
            {
                addProduct(returnProduct(line));
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public void saveProduct()
    {
        try(
                PrintWriter pw = new PrintWriter(new FileWriter(filepath));
                ){
            System.out.println("正在保存数据到库存文件.txt中...");
            for (Product product : products) {
                pw.println(product.getName() + "," + product.getPrice() + "," + product.getQuantity());
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public void addProduct(Product p) {
        products.add(p);
    }

    public void addProductQuantity(Product p) {
        if(!products.contains(p))
        {
            addProduct(p);
            return;
        }
        for (Product product : products) {
            if(product.equals(p)) {
                product.addQuantity(p.getQuantity());
            }
        }
    }

    public void subtractProductQuantity(Product p) {
        if(!products.contains(p)) {
            throw new RuntimeException("商品不存在");
        }
        for (Product product : products) {
            if(product.equals(p)) {
                product.subtractQuantity(p.getQuantity());
            }
        }
    }

    public String findProductByName(String name) {
        List<Product> productList = products.stream().filter(p -> p.getName().equals(name)).toList();
        if(productList.isEmpty()) {
            return "商品不存在";
        }
        StringBuilder sb = new StringBuilder();
        for (Product product : productList) {
            sb.append(product.toString());
            sb.append("============\n");
        }
        return sb.toString();
    }

    public String showProducts()
    {
        if(products.isEmpty()) {
            return "仓库为空，赶快添加内容吧~";
        }
        StringBuilder sb = new StringBuilder();
        for (Product product : products) {
            sb.append(product.toString());
            sb.append("============\n");
        }
        return sb.toString();
    }

    public Product returnProduct(String line)
    {
        String[] str = line.split(",");
        return new Product(str[0], Double.parseDouble(str[1]), Integer.parseInt(str[2]));
    }
}
